﻿#include "ThreeDCloudMapSidebarSettings.h"
#include "ui_ThreeDCloudMapSidebarSettings.h"
#include <QVBoxLayout>
#include <QObject>
#include <QLabel>
#include <QLineEdit>
#include <QSpinBox>
#include <QComboBox>
#include <QWidget>
#include <QRegExp>
#include <QTabWidget>
#include <QTabBar>
#include <QScrollBar>
#include <QListView>
#include <QDebug>
#include <QIcon>
#include <QStandardItemModel>
#include <QListWidgetItem>
#include <QGroupBox>
#include <QCheckBox>
#include <QPushButton>
#include "FormulaEditorDialog.h"
#include "BaseModule/IBaseSignal.h"
#include "BaseModule/GlobalHelper.h"
#include "BaseWidget/IdaDialogMsg.h"
#include "BaseWidget/IWidgetSignal.h"

namespace pst
{
    ThreeDCloudMapSidebarSettings::ThreeDCloudMapSidebarSettings(QWidget* parent)
        : QWidget(parent)
        //, m_page1CentralWidget{ nullptr }
        //, m_tabWidget{ nullptr }
        //, _page1Layout{ nullptr }
        ,
        _titleFontSize{ 14 }, ui(new Ui::ThreeDCloudMapSidebarSettings())
    {
        ui->setupUi(this);
        // 设置基本布局属性
        // setFixedWidth(300);
        setContentsMargins(0, 0, 0, 0);
        addTopTabPivotUI();
        initConnection();
        clearControlPlane();
        ui->dockWidget_Data->setStyleSheet("QDockWidget > QWidget{border: 1px solid #EBEDEE;}");
        ui->dockWidget_DataSource->setStyleSheet("QDockWidget > QWidget{border: 1px solid #EBEDEE;}");
        ui->dockWidget_2->setStyleSheet("QDockWidget > QWidget{border: 1px solid #EBEDEE;}");
        ui->dockWidget_3->setStyleSheet("QDockWidget > QWidget{border: 1px solid #EBEDEE;}");
        ui->scrollArea->setStyleSheet("QScrollArea > QWidget{border: 0px solid #EBEDEE;}");
        ui->listWidget_Data->setWordWrap(true);
        connect(ui->listWidget_Data, &QListWidget::itemChanged, this, &ThreeDCloudMapSidebarSettings::slot_itemCheckStateChanged);
        ui->lineEdit_FormulaEditor->setPlaceholderText(QStringLiteral("self"));
        m_enableStatus.resize(10);
        hideComponents();
        connectSignalsAndSlots();
    }

    ThreeDCloudMapSidebarSettings::~ThreeDCloudMapSidebarSettings()
    {
    }

    void ThreeDCloudMapSidebarSettings::addTopTabPivotUI()
    {
        // m_page1CentralWidget = new QWidget(this);
        //_page1Layout = new QVBoxLayout(m_page1CentralWidget);

        // QGridLayout* la = new QGridLayout(this);
        // la->addWidget(m_page1CentralWidget);

        // m_page1CentralWidget->setLayout(_page1Layout);

        addCurveListUI();
        addDataPageUI();
        addDataOptrationUI();
        //_page1Layout->addStretch();
    }

    void ThreeDCloudMapSidebarSettings::addDataPageUI()
    {
        // QGroupBox* dataGroup = new QGroupBox("筛选数据", this);
        // QVBoxLayout* layout = new QVBoxLayout(dataGroup);

        // 求解类型
        // QLabel* showTypeText = new QLabel("显示类型", this);
        // showTypeText->setTextPixelSize(_titleFontSize);
        // ui->comboBox_DisplayType = new QComboBox(this);

        // layout->addWidget(showTypeText);
        // layout->addWidget(ui->comboBox_DisplayType);

        // 固定值
        // QLabel* fixedValueText = new QLabel("固定值", this);
        // fixedValueText->setTextPixelSize(_titleFontSize);
        // QLabel* fixedParameterText = new QLabel("参数", this);
        // ui->comboBox_FixedValue = new QComboBox(this);
        // QHBoxLayout* fixedValueLayout = new QHBoxLayout();
        // fixedValueLayout->setStretch(0, 1);
        // fixedValueLayout->setStretch(1, 5);
        // layout->addWidget(fixedValueText);
        // fixedValueLayout->addWidget(fixedParameterText);
        // fixedValueLayout->addWidget(ui->comboBox_FixedValue);
        // layout->addWidget(fixedValueText);
        // layout->addWidget(fixedParameterText);
        // layout->addLayout(fixedValueLayout);

        // 结果数据
        // QLabel* resultDataText = new QLabel("结果数据", this);
        // ui->comboBox_valueData = new QComboBox(this);
        // layout->addWidget(resultDataText);
        // layout->addWidget(ui->comboBox_valueData);

        // 类别
        // QLabel* categoryText = new QLabel("类别", this);
        // categoryText->setTextPixelSize(_titleFontSize);
        // ui->comboBox_categryValue = new QComboBox(this);
        ui->comboBox_categryValue->setEnabled(false);
        // layout->addWidget(categoryText);
        // layout->addWidget(ui->comboBox_categryValue);

        //_page1Layout->addWidget(dataGroup);
    }

    void ThreeDCloudMapSidebarSettings::addCurveListUI()
    {
        // QLabel* listText = new QLabel("图形", this);
        // listText->setTextPixelSize(_titleFontSize);
        // ui->listWidget_Data = new QListWidget(this);
        // ui->listWidget_Data->setFixedHeight(150);
        ui->listWidget_Data->setSelectionMode(QAbstractItemView::ExtendedSelection);
        ui->listWidget_Data->setEditTriggers(QAbstractItemView::NoEditTriggers);
        ui->listWidget_Data->setSelectionMode(QAbstractItemView::SingleSelection);
        // QStandardItemModel* model = new QStandardItemModel(ui->listWidget_Data);
        // for (size_t i = 0; i < 10; i++)
        //{
        //     model->appendRow(new QStandardItem(QString("曲线%1").arg(i)));
        // }
        // ui->listWidget_Data->setModel(model);
        // QScrollBar* listViewFloatScrollBar = new QScrollBar(ui->listWidget_Data);
        // listViewFloatScrollBar->setIsAnimation(true);

        // QVBoxLayout* listLayout = new QVBoxLayout();
        // listLayout->addWidget(ui->listWidget_Data);

        //_page1Layout->addWidget(listText);
        //_page1Layout->addLayout(listLayout);

        //connect(ui->listWidget_Data->selectionModel(), &QItemSelectionModel::selectionChanged, this, &ThreeDCloudMapSidebarSettings::slot_curveNameClicked);
        //connect(ui->listWidget_Data, &QListWidget::itemChanged, this, &ThreeDCloudMapSidebarSettings::slot_itemCheckStateChanged);
        //connect(ui->listWidget_Data, &QListWidget::itemDoubleClicked, this, &ThreeDCloudMapSidebarSettings::slot_itemDoubleClicked);
        //connect(ui->listWidget_Data->itemDelegate(), &QAbstractItemDelegate::closeEditor, this, &ThreeDCloudMapSidebarSettings::signal_renameCheck);

        ui->listWidget_Data->setContextMenuPolicy(Qt::CustomContextMenu);
        //QObject::connect(ui->listWidget_Data, &QListWidget::customContextMenuRequested,
        //    this, &ThreeDCloudMapSidebarSettings::slot_addCustomContextMenu);
        // ui->listWidget_Data->model()->sele
    }

    void ThreeDCloudMapSidebarSettings::addDataOptrationUI()
    {
        // QGroupBox* dataGroup = new QGroupBox("数据处理", this);
        // QVBoxLayout* layout = new QVBoxLayout(dataGroup);

        // ui->checkBox_DB = new QCheckBox("取对数", this);
        ui->checkBox_DB->setEnabled(false);
        // ui->checkBox_Normalize = new QCheckBox("归一化", this);
        ui->checkBox_Normalize->setEnabled(false);
        // m_checkBoxMathOp = new QCheckBox("数学运算", this);
        ui->checkBox_MathOperation->setEnabled(false);
        // QLineEdit* m_mathOpLineEdit = new QLineEdit(this);
        ui->lineEdit_FormulaEditor->setReadOnly(true);
        // QPushButton* m_mathEditButton = new QPushButton("公式编辑器", this);
        ui->pushButton_FormulaEditor->setEnabled(false);

        // layout->addWidget(ui->checkBox_DB);
        // layout->addWidget(ui->checkBox_Normalize);
        // layout->addWidget(m_checkBoxMathOp);
        // layout->addWidget(m_mathOpLineEdit);
        // layout->addWidget(m_mathEditButton);
        //_page1Layout->addWidget(dataGroup);
    }

    void ThreeDCloudMapSidebarSettings::setMainWiondowId(int id)
    {
        m_mainWindowId = id;
    }

    QListWidgetItem* ThreeDCloudMapSidebarSettings::addData(InfomationGraph3DBasical* info)
    {
        // auto item = new QStandardItem(curveName);
        QString curveName = info->m_name;
        QListWidgetItem* listItem = new QListWidgetItem(curveName);
        listItem->setFlags(listItem->flags() | Qt::ItemIsUserCheckable);
        listItem->setCheckState(Qt::Checked);
        ui->listWidget_Data->addItem(listItem);

        m_allAddedDataList.append(qMakePair(info, listItem));
        return listItem;
    }

    // void ThreeDCloudMapSidebarSettings::setSlicePositionEnum(const QList<double>& xSliceEnum,
    //     const QList<double>& ySliceEnum, const QList<double>& zSliceEnum)
    //{
    //     m_xSliceEnum = xSliceEnum;
    //     m_ySliceEnum = ySliceEnum;
    //     m_zSliceEnum = zSliceEnum;
    // }

    // 选中曲线后，判断所有选中曲线的信息，根据信息设置下面框的内内容
    void ThreeDCloudMapSidebarSettings::slot_curveNameClicked()
    {
        // TODO 发送信号给graph，通知选中该曲线
        auto allSelectedItem = ui->listWidget_Data->selectedItems();
        QString dataSource;
        bool _isLegalSource = true;
        QList<int> selectedItemIndexList;
        for (auto item : allSelectedItem)
        {
            selectedItemIndexList.append(ui->listWidget_Data->row(item));
            if (_isLegalSource)
            {
                // 获取数据来源（项目树）
                QString _itemText;
                emit signal_getSidebarCurveDataSource(item, _itemText);
                if (dataSource.isEmpty() || dataSource.contains(_itemText))
                    dataSource = _itemText;
                else
                {
                    dataSource = "";
                    _isLegalSource = false;
                }
            }
        }
        ui->textEdit_DataSource->setText(dataSource);
        QString selectedItemIndexListString = GlobalHelperInstance->convertIntListToQString(selectedItemIndexList);

        QStringList _pyCodes{};
        _pyCodes += QString("threedcloudmapsidebarsettings1 = PostProcessing.ThreeDCloudMapSidebarSettingsPy()");
        _pyCodes += QString("threedcloudmapsidebarsettings1.curveNameClicked(%1,'%2')").arg((int)m_mainWindowId).arg(selectedItemIndexListString);
        emit IBaseSignalInstance->signal_execPYCode(_pyCodes, true, false);
        pyCurveNameClicked(selectedItemIndexList);
    }

    void ThreeDCloudMapSidebarSettings::on_pushButton_FormulaEditor_clicked()
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        QStringList _SelectionCurve{
            QStringLiteral("曲线1"),
        };
        auto _formulaEditorDialog = new FormulaEditorDialog();
        _formulaEditorDialog->setCurveList(_SelectionCurve);
        auto _ok = _formulaEditorDialog->execWindow();
        if (_ok)
        {
            auto _formulaContent = _formulaEditorDialog->getFormulaContent();
            ui->lineEdit_FormulaEditor->setText(_formulaContent);
        }
    }

    void ThreeDCloudMapSidebarSettings::on_radioButton_Amplitude_clicked()
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        auto _isClicked = ui->radioButton_Amplitude->isChecked();
        m_currentItemData->setCurrentComponentIndex(0);
        {
            QSignalBlocker blocker(ui->checkBox_DB);
            ui->checkBox_DB->setEnabled(true);
            ui->checkBox_DB->setChecked(m_currentItemData->getIsLog());
        }
        emit signal_updateActorValue(m_currentItemData);
    }
    void ThreeDCloudMapSidebarSettings::on_radioButton_Phase_clicked()
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        auto _isClicked = ui->radioButton_Phase->isChecked();
        m_currentItemData->setCurrentComponentIndex(1);
        {
            //m_currentItemData->setIsLog(false);
            QSignalBlocker blocker(ui->checkBox_DB);
            ui->checkBox_DB->setEnabled(false);
            ui->checkBox_DB->setChecked(false);
        }
        emit signal_updateActorValue(m_currentItemData);
    }
    void ThreeDCloudMapSidebarSettings::on_radioButton_RealPart_clicked()
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        auto _isClicked = ui->radioButton_RealPart->isChecked();
        m_currentItemData->setCurrentComponentIndex(2);
        {
            //m_currentItemData->setIsLog(false);
            QSignalBlocker blocker(ui->checkBox_DB);
            ui->checkBox_DB->setEnabled(false);
            ui->checkBox_DB->setChecked(false);
        }
        emit signal_updateActorValue(m_currentItemData);
    }
    void ThreeDCloudMapSidebarSettings::on_radioButton_ImaginaryPart_clicked()
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        auto _isClicked = ui->radioButton_ImaginaryPart->isChecked();
        m_currentItemData->setCurrentComponentIndex(3);
        {
            //m_currentItemData->setIsLog(false);
            QSignalBlocker blocker(ui->checkBox_DB);
            ui->checkBox_DB->setEnabled(false);
            ui->checkBox_DB->setChecked(false);
        }
        emit signal_updateActorValue(m_currentItemData);
    }

    void ThreeDCloudMapSidebarSettings::slot_itemCheckStateChanged(QListWidgetItem* item)
    {
        auto index = ui->listWidget_Data->row(item);
        auto visible = item->checkState() == Qt::Checked ? true : false;

        QStringList _pyCodes{};
        _pyCodes += QString("threedcloudmapsidebarsettings2 = PostProcessing.ThreeDCloudMapSidebarSettingsPy()");
        _pyCodes += QString("threedcloudmapsidebarsettings2.itemCheckStateChanged(%1,%2,%3)").arg((int)m_mainWindowId).arg((int)index).arg(visible);
        emit IBaseSignalInstance->signal_execPYCode(_pyCodes, true, false);
        pyItemCheckStateChanged(index, visible);
    }

    void ThreeDCloudMapSidebarSettings::slot_itemDoubleClicked(QListWidgetItem* item)
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        siganl_graphNameDoubleClicked(item);
    }

    //void ThreeDCloudMapSidebarSettings::slot_normalizeClicked(bool checked)
    //{
    //    auto isLoged = ui->checkBox_DB->isChecked();
    //    auto isNormalized = ui->checkBox_Normalize->isChecked();

    //    QStringList _pyCodes{};
    //    _pyCodes += QString("threedcloudmapsidebarsettings3 = PostProcessing.ThreeDCloudMapSidebarSettingsPy()");
    //    _pyCodes += QString("threedcloudmapsidebarsettings3.setDataOprationChanged(%1,%2,%3)").arg((int)m_mainWindowId).arg((int)isLoged).arg((int)isNormalized);
    //    emit IBaseSignalInstance->signal_execPYCode(_pyCodes);
    //}

    //void ThreeDCloudMapSidebarSettings::slot_logClicked(bool checked)
    //{
    //    auto isLoged = ui->checkBox_DB->isChecked();
    //    auto isNormalized = ui->checkBox_Normalize->isChecked();

    //    QStringList _pyCodes{};
    //    _pyCodes += QString("threedcloudmapsidebarsettings4 = PostProcessing.ThreeDCloudMapSidebarSettingsPy()");
    //    _pyCodes += QString("threedcloudmapsidebarsettings4.setDataOprationChanged(%1,%2,%3)").arg((int)m_mainWindowId).arg((int)isLoged).arg((int)isNormalized);
    //    emit IBaseSignalInstance->signal_execPYCode(_pyCodes);
    //}

    void ThreeDCloudMapSidebarSettings::slot_updateFixedParameter(int index)
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        QStringList _pyCodes{};
        _pyCodes += QString("threedcloudmapsidebarsettings5 = PostProcessing.ThreeDCloudMapSidebarSettingsPy()");
        _pyCodes += QString("threedcloudmapsidebarsettings5.updateFixedParameter(%1,%2)").arg((int)m_mainWindowId).arg((int)index);
        emit IBaseSignalInstance->signal_execPYCode(_pyCodes);
        this->updateFixedParameter(index);
        emit signal_updateOrignalData(m_currentItemData);
    }

    void ThreeDCloudMapSidebarSettings::slot_updateOriginalDataSource(int index)
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        int showType = ui->comboBox_DisplayType->currentIndex();
        int fixedValueIndex = ui->comboBox_FixedValue->currentIndex();
        bool isLog = ui->checkBox_DB->isChecked();
        bool isNormalize = ui->checkBox_Normalize->isChecked();
        QStringList _pyCodes{};
        _pyCodes += QString("threedcloudmapsidebarsettings6 = PostProcessing.ThreeDCloudMapSidebarSettingsPy()");
        _pyCodes += QString("threedcloudmapsidebarsettings6.updateOriginalDataSource(%1,%2,%3,%4,%5,%6)").arg(m_mainWindowId).arg(index).arg(showType).arg(fixedValueIndex).arg((int)isLog).arg((int)isNormalize);
        emit IBaseSignalInstance->signal_execPYCode(_pyCodes, true, false);

        pyUpdateOriginalDataSource(index, showType, fixedValueIndex, isLog, isNormalize);
    }

    void ThreeDCloudMapSidebarSettings::slot_resultDataChanged(int index)
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        m_currentItemData->setCurrentValueGroupNameIndex(index);
        updateGroupRadioButtonUI(m_currentItemData);

        //QStringList _pyCodes{};
        //_pyCodes += QString("threedcloudmapsidebarsettings7 = PostProcessing.ThreeDCloudMapSidebarSettingsPy()");
        //_pyCodes += QString("threedcloudmapsidebarsettings7.resultDataChanged(%1,%2)").arg((int)m_mainWindowId).arg((int)index);
        //emit IBaseSignalInstance->signal_execPYCode(_pyCodes);
        //emit signal_updateActorValue(m_currentItemData);
        emit signal_updateOrignalData(m_currentItemData);

    }

    void ThreeDCloudMapSidebarSettings::initConnection()
    {
    }

    void ThreeDCloudMapSidebarSettings::updateInfoDataAndInterfaceToUI(ThreeDCloudMapSidebarData* data)
    {
        //disconnectSignalsAndSlots();
        QSignalBlocker blocker1(ui->comboBox_DisplayType);
        QSignalBlocker blocker2(ui->comboBox_FixedValue);
        QSignalBlocker blocker3(ui->comboBox_valueData);
        QSignalBlocker blocker4(ui->checkBox_DB);
        QSignalBlocker blocker5(ui->checkBox_Normalize);
        QSignalBlocker blocker6(ui->listWidget_Data);


        clearControlPlane();
        m_currentItemData = data;
        ui->comboBox_DisplayType->addItem("表面");
        ui->comboBox_DisplayType->addItem("XOY");
        ui->comboBox_DisplayType->addItem("YOZ");
        ui->comboBox_DisplayType->addItem("ZOX");

        //ui->checkBox_DB->setEnabled(true);
        //ui->checkBox_DB->setChecked(data->getIsLog());

        ui->checkBox_Normalize->setEnabled(true);
        ui->checkBox_Normalize->setChecked(data->getIsNormalized());

        ui->comboBox_DisplayType->setCurrentIndex(data->getCurrentShowType());
        //slot_updateFixedParameter(data->getCurrentShowType());

        int currentFixedParamIndex = data->getCurrentFixedParamIndex();
        updateFixedParameter(data->getCurrentShowType());//会修改currentFixedParamIndex
        data->setCurrentFixedParamIndex(currentFixedParamIndex);
        //emit signal_updateOrignalData(m_currentItemData);

        double num = 0;
        QString sliceUnit = "";
        switch (data->getCurrentShowType())
        {
        case 0:
            break;
        case 1:
        {
            num = data->getZSliceEnum()[data->getCurrentFixedParamIndex()];
            sliceUnit = data->getZSliceUnit();
            break;
        }
        case 2:
        {
            num = data->getXSliceEnum()[data->getCurrentFixedParamIndex()];
            sliceUnit = data->getXSliceUnit();
            break;
        }
        case 3:
        {
            num = data->getYSliceEnum()[data->getCurrentFixedParamIndex()];
            sliceUnit = data->getYSliceUnit();
            break;
        }
        break;
        default:
            break;
        }
        QSignalBlocker blocker(ui->comboBox_FixedValue);
        ui->comboBox_FixedValue->setCurrentText(QString::number(num));
        ui->label_Unit->setText(sliceUnit);

        auto valueNameList = data->getValueGroupNameList();
        for (const auto& i : valueNameList)
        {
            ui->comboBox_valueData->addItem(i);
        }
        ui->comboBox_valueData->setCurrentIndex(data->getCurrentValueGroupNameIndex());
        ui->textEdit_DataSource->setText(data->getDataSource());

        updateGroupRadioButtonUI(data);
        // ui->checkBox_DB->setEnabled(true);
        // ui->checkBox_Normalize->setEnabled(true);

        //connectSignalsAndSlots();
    }

    void ThreeDCloudMapSidebarSettings::updateInfoValueToUI(ThreeDCloudMapSidebarData* data)
    {
        // auto valueList = data->getValueList();
        // auto frequencyList = data->getFrequencyList();
        // for (const auto i : frequencyList)
        //{
        //     ui->comboBox_FixedValue->addItem(QString::number(i));
        // }
        // ui->comboBox_FixedValue->setCurrentText(QString::number(data->getCurrentFrequency()));

        // for (const auto& i : valueList)
        //{
        //     ui->comboBox_valueData->addItem(i);
        // }
        // ui->comboBox_valueData->setCurrentIndex(data->getCurrentValueIndex());
        // ui->checkBox_DB->setChecked(data->getIsLog());
        // ui->checkBox_Normalize->setChecked(data->getIsNormalize());
    }

    void ThreeDCloudMapSidebarSettings::connectSignalsAndSlots()
    {
        connect(ui->comboBox_DisplayType, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ThreeDCloudMapSidebarSettings::slot_updateFixedParameter, Qt::UniqueConnection);
        connect(ui->comboBox_FixedValue, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ThreeDCloudMapSidebarSettings::slot_updateOriginalDataSource, Qt::UniqueConnection);
        connect(ui->comboBox_valueData, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ThreeDCloudMapSidebarSettings::slot_resultDataChanged);
        connect(ui->checkBox_DB, &QCheckBox::clicked, this, &ThreeDCloudMapSidebarSettings::slot_updateOriginalDataSource, Qt::UniqueConnection);
        connect(ui->checkBox_Normalize, &QCheckBox::clicked, this, &ThreeDCloudMapSidebarSettings::slot_updateOriginalDataSource, Qt::UniqueConnection);
        //connect(ui->checkBox_Normalize, &QCheckBox::clicked, this, &ThreeDCloudMapSidebarSettings::slot_normalizeClicked);
        //connect(ui->checkBox_DB, &QCheckBox::clicked, this, &ThreeDCloudMapSidebarSettings::slot_logClicked);

        connect(ui->listWidget_Data->selectionModel(), &QItemSelectionModel::selectionChanged, this, &ThreeDCloudMapSidebarSettings::slot_curveNameClicked,Qt::UniqueConnection);
        //connect(ui->listWidget_Data, &QListWidget::itemChanged, this, &ThreeDCloudMapSidebarSettings::slot_itemCheckStateChanged);
        connect(ui->listWidget_Data, &QListWidget::itemDoubleClicked, this, &ThreeDCloudMapSidebarSettings::slot_itemDoubleClicked, Qt::UniqueConnection);
        connect(ui->listWidget_Data->itemDelegate(), &QAbstractItemDelegate::closeEditor, this, &ThreeDCloudMapSidebarSettings::signal_renameCheck, Qt::UniqueConnection);

        QObject::connect(ui->listWidget_Data, &QListWidget::customContextMenuRequested,
            this, &ThreeDCloudMapSidebarSettings::slot_addCustomContextMenu);

        //connect(ui->comboBox_DisplayType, &PostComboBox::popupAboutToShow, this, [](){
        //emit IWidgetSignalInstance->signal_exitAddMarkerState(); });
        //connect(ui->comboBox_FixedValue, &PostComboBox::popupAboutToShow, this, [](){
        //emit IWidgetSignalInstance->signal_exitAddMarkerState(); });
        //connect(ui->comboBox_valueData, &PostComboBox::popupAboutToShow, this, [](){
        //emit IWidgetSignalInstance->signal_exitAddMarkerState(); });

    }

    void ThreeDCloudMapSidebarSettings::disconnectSignalsAndSlots()
    {
        disconnect(ui->comboBox_DisplayType, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ThreeDCloudMapSidebarSettings::slot_updateFixedParameter);
        disconnect(ui->comboBox_FixedValue, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ThreeDCloudMapSidebarSettings::slot_updateOriginalDataSource);
        disconnect(ui->comboBox_valueData, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ThreeDCloudMapSidebarSettings::slot_resultDataChanged);
        disconnect(ui->checkBox_DB, &QCheckBox::clicked, this, &ThreeDCloudMapSidebarSettings::slot_updateOriginalDataSource);
        disconnect(ui->checkBox_Normalize, &QCheckBox::clicked, this, &ThreeDCloudMapSidebarSettings::slot_updateOriginalDataSource);
        //disconnect(ui->checkBox_Normalize, &QCheckBox::clicked, this, &ThreeDCloudMapSidebarSettings::slot_normalizeClicked);
        //disconnect(ui->checkBox_DB, &QCheckBox::clicked, this, &ThreeDCloudMapSidebarSettings::slot_logClicked);

        disconnect(ui->listWidget_Data->selectionModel(), &QItemSelectionModel::selectionChanged, this, &ThreeDCloudMapSidebarSettings::slot_curveNameClicked);
        //disconnect(ui->listWidget_Data, &QListWidget::itemChanged, this, &ThreeDCloudMapSidebarSettings::slot_itemCheckStateChanged);
        disconnect(ui->listWidget_Data, &QListWidget::itemDoubleClicked, this, &ThreeDCloudMapSidebarSettings::slot_itemDoubleClicked);
        disconnect(ui->listWidget_Data->itemDelegate(), &QAbstractItemDelegate::closeEditor, this, &ThreeDCloudMapSidebarSettings::signal_renameCheck);

        QObject::disconnect(ui->listWidget_Data, &QListWidget::customContextMenuRequested,
            this, &ThreeDCloudMapSidebarSettings::slot_addCustomContextMenu);
    }

    void ThreeDCloudMapSidebarSettings::hideComponents()
    {
        ui->label_categryValue->setVisible(false);
        ui->comboBox_categryValue->setVisible(false);
        ui->checkBox_MathOperation->setVisible(false);
        ui->lineEdit_FormulaEditor->setVisible(false);
        ui->pushButton_FormulaEditor->setVisible(false);
        ui->groupBox_fixedValue->hide();

        ui->radioButton_Amplitude->setEnabled(false);     // 幅度
        ui->radioButton_Phase->setEnabled(false);         // 相位
        ui->radioButton_RealPart->setEnabled(false);      // 实部
        ui->radioButton_ImaginaryPart->setEnabled(false); // 虚部
    }

    void ThreeDCloudMapSidebarSettings::updateFixedParameter(int index)
    {
        if (m_currentItemData == nullptr)
        {
            return;
        }

        switch (index)
        {
        case 0:
            ui->comboBox_FixedValue->clear();
            ui->comboBox_FixedValue->setEnabled(false);

            ui->groupBox_fixedValue->hide();
            break;

        case 1:
        {
            disconnect(ui->comboBox_FixedValue, QOverload<int>::of(&QComboBox::currentIndexChanged),
                this, &ThreeDCloudMapSidebarSettings::slot_updateOriginalDataSource);
            ui->comboBox_FixedValue->clear();
            ui->comboBox_FixedValue->setEnabled(true);
            for (auto i : m_currentItemData->getZSliceEnum())
            {
                ui->comboBox_FixedValue->addItem(QString::number(i));
            }
            ui->comboBox_FixedValue->setCurrentIndex(0);
            double position = ui->comboBox_FixedValue->currentText().toDouble();
            m_currentItemData->setCurrentShowType(index);
            m_currentItemData->setCurrentFixedParamIndex(0);

            ui->groupBox_fixedValue->setHidden(false);
            ui->label_FixedValue->setText("Z位置");
            ui->label_Unit->setText(m_currentItemData->getZSliceUnit());

            connect(ui->comboBox_FixedValue, QOverload<int>::of(&QComboBox::currentIndexChanged),
                this, &ThreeDCloudMapSidebarSettings::slot_updateOriginalDataSource);
            break;
        }

        case 2:
        {
            disconnect(ui->comboBox_FixedValue, QOverload<int>::of(&QComboBox::currentIndexChanged),
                this, &ThreeDCloudMapSidebarSettings::slot_updateOriginalDataSource);
            ui->comboBox_FixedValue->clear();
            ui->comboBox_FixedValue->setEnabled(true);
            for (auto i : m_currentItemData->getXSliceEnum())
            {
                ui->comboBox_FixedValue->addItem(QString::number(i));
            }
            ui->comboBox_FixedValue->setCurrentIndex(0);
            double position = ui->comboBox_FixedValue->currentText().toDouble();
            m_currentItemData->setCurrentShowType(index);
            m_currentItemData->setCurrentFixedParamIndex(0);
            //emit signal_updateOrignalData(m_currentItemData);

            ui->groupBox_fixedValue->setHidden(false);
            ui->label_FixedValue->setText("X位置");
            ui->label_Unit->setText(m_currentItemData->getXSliceUnit());

            connect(ui->comboBox_FixedValue, QOverload<int>::of(&QComboBox::currentIndexChanged),
                this, &ThreeDCloudMapSidebarSettings::slot_updateOriginalDataSource);
            break;
        }
        case 3:
        {
            disconnect(ui->comboBox_FixedValue, QOverload<int>::of(&QComboBox::currentIndexChanged),
                this, &ThreeDCloudMapSidebarSettings::slot_updateOriginalDataSource);
            ui->comboBox_FixedValue->clear();
            ui->comboBox_FixedValue->setEnabled(true);
            for (auto i : m_currentItemData->getYSliceEnum())
            {
                ui->comboBox_FixedValue->addItem(QString::number(i));
            }
            ui->comboBox_FixedValue->setCurrentIndex(0);
            double position = ui->comboBox_FixedValue->currentText().toDouble();
            m_currentItemData->setCurrentShowType(index);
            m_currentItemData->setCurrentFixedParamIndex(0);
            //emit signal_updateOrignalData(m_currentItemData);

            ui->groupBox_fixedValue->setHidden(false);
            ui->label_FixedValue->setText("Y位置");
            ui->label_Unit->setText(m_currentItemData->getYSliceUnit());

            connect(ui->comboBox_FixedValue, QOverload<int>::of(&QComboBox::currentIndexChanged),
                this, &ThreeDCloudMapSidebarSettings::slot_updateOriginalDataSource);
            break;
        }

        default:
            break;
        }
    }

    void ThreeDCloudMapSidebarSettings::clearControlPlane()
    {
        QSignalBlocker blocker(ui->comboBox_valueData);
        QSignalBlocker blocker1(ui->comboBox_DisplayType);
        QSignalBlocker blocker2(ui->comboBox_FixedValue);
        QSignalBlocker blocker3(ui->checkBox_DB);
        QSignalBlocker blocker4(ui->checkBox_Normalize);

        ui->comboBox_DisplayType->clear();
        ui->comboBox_FixedValue->clear();
        ui->comboBox_valueData->clear();
        ui->checkBox_DB->setChecked(false);
        ui->checkBox_DB->setEnabled(false);
        ui->checkBox_Normalize->setChecked(false);
        ui->checkBox_Normalize->setEnabled(false);

        QSignalBlocker blocker5(ui->radioButton_RealPart);
        QSignalBlocker blocker6(ui->radioButton_ImaginaryPart);
        QSignalBlocker blocker7(ui->radioButton_Amplitude);
        QSignalBlocker blocker8(ui->radioButton_Phase);

        QList<QRadioButton*> radios = {
        ui->radioButton_RealPart, ui->radioButton_ImaginaryPart,
        ui->radioButton_Amplitude, ui->radioButton_Phase };

        for (auto* rb : radios)
        {
            rb->setAutoExclusive(false);
            rb->setChecked(false);
            rb->setEnabled(false);
        }
    }

    void ThreeDCloudMapSidebarSettings::setControlPanelEditable(bool enable)
    {
        // enable?
        // ui->listWidget_Data->setSelectionMode(QAbstractItemView::SingleSelection):
        // ui->listWidget_Data->setSelectionMode(QAbstractItemView::NoSelection);

        ui->comboBox_DisplayType->setEnabled(enable);
        ui->comboBox_FixedValue->setEnabled(enable);
        ui->comboBox_valueData->setEnabled(enable);
        ui->comboBox_categryValue->setEnabled(enable);

        ui->radioButton_Amplitude->setEnabled(enable);     // 幅度
        ui->radioButton_Phase->setEnabled(enable);         // 相位
        ui->radioButton_RealPart->setEnabled(enable);      // 实部
        ui->radioButton_ImaginaryPart->setEnabled(enable); // 虚部

        ui->checkBox_DB->setEnabled(enable);
        ui->checkBox_Normalize->setEnabled(enable);
    }

    QListWidget* ThreeDCloudMapSidebarSettings::getCurveNameListWidget()
    {
        return ui->listWidget_Data;
    }

    void ThreeDCloudMapSidebarSettings::setControlPlaneToAnimationState(bool isAnimationState)
    {
        if (isAnimationState)
        {
            disconnectSignalsAndSlots();

            m_enableStatus[0] = ui->comboBox_DisplayType->isEnabled();
            m_enableStatus[1] = ui->comboBox_FixedValue->isEnabled();
            m_enableStatus[2] = ui->comboBox_valueData->isEnabled();
            m_enableStatus[3] = ui->radioButton_Amplitude->isEnabled();
            m_enableStatus[4] = ui->radioButton_Phase->isEnabled();
            m_enableStatus[5] = ui->radioButton_RealPart->isEnabled();
            m_enableStatus[6] = ui->radioButton_ImaginaryPart->isEnabled();
            m_enableStatus[7] = ui->comboBox_categryValue->isEnabled();
            m_enableStatus[8] = ui->checkBox_DB->isEnabled();
            m_enableStatus[9] = ui->checkBox_Normalize->isEnabled();

            setControlPanelEditable(false);
        }
        else
        {
            connectSignalsAndSlots();

            ui->comboBox_DisplayType->setEnabled(m_enableStatus[0]);
            ui->comboBox_FixedValue->setEnabled(m_enableStatus[1]);
            ui->comboBox_valueData->setEnabled(m_enableStatus[2]);
            ui->radioButton_Amplitude->setEnabled(m_enableStatus[3]);
            ui->radioButton_Phase->setEnabled(m_enableStatus[4]);
            ui->radioButton_RealPart->setEnabled(m_enableStatus[5]);
            ui->radioButton_ImaginaryPart->setEnabled(m_enableStatus[6]);
            ui->comboBox_categryValue->setEnabled(m_enableStatus[7]);
            ui->checkBox_DB->setEnabled(m_enableStatus[8]);
            ui->checkBox_Normalize->setEnabled(m_enableStatus[9]);
        }
    }

    void ThreeDCloudMapSidebarSettings::slot_addCustomContextMenu(const QPoint& pos)
    {
        auto selectedItems = ui->listWidget_Data->selectedItems();
        if (selectedItems.isEmpty())
        {
            return;
        }

        QMenu contextMenu(this);
        QAction* deleteChosenGraphs = contextMenu.addAction("删除选中的图像");
        QObject::connect(deleteChosenGraphs, &QAction::triggered, this,
            [this]()
            {
                emit IWidgetSignalInstance->signal_exitAddMarkerState();

                QList<QListWidgetItem*> itemList = ui->listWidget_Data->selectedItems();
                QString selectedIndexs;
                for (QListWidgetItem* item : itemList)
                {
                    int rowIndex = ui->listWidget_Data->row(item);
                    selectedIndexs.append("_").append(QString::number(rowIndex));
                }
                selectedIndexs = "'" + selectedIndexs.right(selectedIndexs.length() - 1) + "'";
                QStringList _pyCodes{};
                _pyCodes += QString("threedcloudmapsidebarsettings9 = PostProcessing.ThreeDCloudMapSidebarSettingsPy()");
                _pyCodes += QString("threedcloudmapsidebarsettings9.delete3DCloudMap(%1,%2)").arg((int)m_mainWindowId).arg(selectedIndexs);
                emit IBaseSignalInstance->signal_execPYCode(_pyCodes, true, false);

                emit signal_deleteChosenGraphs(ui->listWidget_Data->selectedItems());
            });

        if (selectedItems.size() == 1)
        {
            QAction* renameGraphs = contextMenu.addAction("重命名");
            QObject::connect(renameGraphs, &QAction::triggered, this, &ThreeDCloudMapSidebarSettings::slot_renameItem);
        }

        contextMenu.exec(ui->listWidget_Data->mapToGlobal(pos));
    }

    void ThreeDCloudMapSidebarSettings::slot_renameItem()
    {
        emit IWidgetSignalInstance->signal_exitAddMarkerState();
        auto selectedItems = ui->listWidget_Data->selectedItems();
        if (selectedItems.size() != 1)
        {
            return;
        }

        auto item = selectedItems[0];
        item->setFlags(item->flags() | Qt::ItemIsEditable);
        ui->listWidget_Data->editItem(item);
    }

    void ThreeDCloudMapSidebarSettings::pyCurveNameClicked(QList<int> selectedIndexs)
    {
        QList<QListWidgetItem*> allSelectedItem;
        {

            QSignalBlocker blocker(ui->listWidget_Data);

            for (int i = 0; i < selectedIndexs.size(); i++)
            {
                QListWidgetItem* item = ui->listWidget_Data->item(selectedIndexs.at(i));
                // 添加nullptr判断，避免程序崩溃问题。
                if (item == nullptr)
                {
                    qDebug() << "pyCurveNameClicked点击到空项目，跳过" << endl;
                    continue;
                }
                item->setSelected(true);
                allSelectedItem.append(item);
            }
        }
        if (allSelectedItem.isEmpty())
        {
            disconnectSignalsAndSlots();
            clearControlPlane();
            connectSignalsAndSlots();
            return;
        }
        ui->pushButton_FormulaEditor->setEnabled(true);
        emit signal_chosenItemsChanged(allSelectedItem);
    }

    void ThreeDCloudMapSidebarSettings::pyUpdateFixedParameter(int index)
    {
        QSignalBlocker blocker(ui->comboBox_DisplayType);
        ui->comboBox_DisplayType->setCurrentIndex(index);

        updateFixedParameter(index);
        emit signal_updateOrignalData(m_currentItemData);

        //if (m_currentItemData == nullptr)
        //{
        //    return;
        //}

        //switch (index)
        //{
        //case 0:
        //    ui->comboBox_FixedValue->clear();
        //    ui->comboBox_FixedValue->setEnabled(false);
        //    break;

        //case 1:
        //    disconnect(ui->comboBox_FixedValue, QOverload<int>::of(&QComboBox::currentIndexChanged),
        //               this, &ThreeDCloudMapSidebarSettings::slot_updateOriginalDataSource);
        //    ui->comboBox_FixedValue->clear();
        //    connect(ui->comboBox_FixedValue, QOverload<int>::of(&QComboBox::currentIndexChanged),
        //            this, &ThreeDCloudMapSidebarSettings::slot_updateOriginalDataSource);
        //    ui->comboBox_FixedValue->setEnabled(true);
        //    for (auto i : m_currentItemData->getZSliceEnum())
        //    {
        //        ui->comboBox_FixedValue->addItem(QString::number(i));
        //    }
        //    ui->comboBox_FixedValue->setCurrentIndex(0);
        //    break;

        //case 2:
        //    disconnect(ui->comboBox_FixedValue, QOverload<int>::of(&QComboBox::currentIndexChanged),
        //               this, &ThreeDCloudMapSidebarSettings::slot_updateOriginalDataSource);
        //    ui->comboBox_FixedValue->clear();
        //    connect(ui->comboBox_FixedValue, QOverload<int>::of(&QComboBox::currentIndexChanged),
        //            this, &ThreeDCloudMapSidebarSettings::slot_updateOriginalDataSource);
        //    ui->comboBox_FixedValue->setEnabled(true);
        //    for (auto i : m_currentItemData->getXSliceEnum())
        //    {
        //        ui->comboBox_FixedValue->addItem(QString::number(i));
        //    }
        //    ui->comboBox_FixedValue->setCurrentIndex(0);
        //    break;

        //case 3:
        //    disconnect(ui->comboBox_FixedValue, QOverload<int>::of(&QComboBox::currentIndexChanged),
        //               this, &ThreeDCloudMapSidebarSettings::slot_updateOriginalDataSource);
        //    ui->comboBox_FixedValue->clear();
        //    connect(ui->comboBox_FixedValue, QOverload<int>::of(&QComboBox::currentIndexChanged),
        //            this, &ThreeDCloudMapSidebarSettings::slot_updateOriginalDataSource);
        //    ui->comboBox_FixedValue->setEnabled(true);
        //    for (auto i : m_currentItemData->getYSliceEnum())
        //    {
        //        ui->comboBox_FixedValue->addItem(QString::number(i));
        //    }
        //    ui->comboBox_FixedValue->setCurrentIndex(0);
        //    break;

        //default:
        //    break;
        //}
    }

    void ThreeDCloudMapSidebarSettings::pyUpdateOriginalDataSource(int index, int showType, int fixedValueIndex, bool isLog, bool isNormalize)
    {
        {
            QSignalBlocker blocker2(ui->comboBox_DisplayType);
            QSignalBlocker blocker1(ui->comboBox_FixedValue);
            QSignalBlocker blocker4(ui->checkBox_DB);
            QSignalBlocker blocker5(ui->checkBox_Normalize);

            ui->comboBox_DisplayType->setCurrentIndex(showType);

            for (int i = 0; i < ui->comboBox_FixedValue->count(); ++i)
            {
                qDebug() << ui->comboBox_FixedValue->itemText(i);

            }
            updateFixedParameter(showType);
            ui->comboBox_FixedValue->setCurrentIndex(fixedValueIndex);
            ui->checkBox_DB->setChecked(isLog);
            ui->checkBox_Normalize->setChecked(isNormalize);
        }

        m_currentItemData->setCurrentShowType(showType);
        m_currentItemData->setCurrentFixedParamIndex(fixedValueIndex);
        m_currentItemData->setIsLog(isLog);
        m_currentItemData->setIsNormalized(isNormalize);
        emit signal_updateOrignalData(m_currentItemData);
    }

    void ThreeDCloudMapSidebarSettings::pyResultDataChanged(int index)
    {
        QSignalBlocker blocker(ui->comboBox_valueData);
        ui->comboBox_valueData->setCurrentIndex(index);
        m_currentItemData->setCurrentValueGroupNameIndex(index);
        updateGroupRadioButtonUI(m_currentItemData);

        //emit signal_updateActorValue(m_currentItemData);
        emit signal_updateOrignalData(m_currentItemData);
    }

    void ThreeDCloudMapSidebarSettings::pyDelete3DCloudMap(QString selectedIndexs)
    {
        QStringList rowIndexsStr = selectedIndexs.split("_");
        QList<QListWidgetItem*> itemList;
        for (QString rowIndexStr : rowIndexsStr)
        {
            int rowIndex = rowIndexStr.toInt();
            itemList.append(ui->listWidget_Data->item(rowIndex));
        }
        emit signal_deleteChosenGraphs(itemList);
    }

    void ThreeDCloudMapSidebarSettings::updateGroupRadioButtonUI(ThreeDCloudMapSidebarData* data)
    {
        QSignalBlocker blocker1(ui->radioButton_Amplitude);
        QSignalBlocker blocker2(ui->radioButton_Phase);
        QSignalBlocker blocker3(ui->radioButton_RealPart);
        QSignalBlocker blocker4(ui->radioButton_ImaginaryPart);
        QSignalBlocker blocker5(ui->checkBox_DB);

        auto textParser = data->getTextFileParser();
        if (textParser == nullptr)
        {
            qDebug() << "TextFileParser is null, cannot update UI.";
            return;
        }
        int currentValueGroupNameIndex = data->getCurrentValueGroupNameIndex();
        int currentComponentIndex = data->getCurrentComponentIndex();

        int realIndex = textParser->getRealValueIndex(currentValueGroupNameIndex, currentComponentIndex);
        auto metaData = textParser->getDataInfoByRealValueIndex(realIndex);
        int resultParaType = metaData.resultParaType;
        int resultDataType = metaData.resultDataType;

        QList<QRadioButton*> radios = {
            ui->radioButton_RealPart, ui->radioButton_ImaginaryPart,
            ui->radioButton_Amplitude, ui->radioButton_Phase };

        // 简化代码，先禁用所有按钮
        for (auto* rb : radios)
        {
            rb->setAutoExclusive(true);
            rb->setEnabled(true);
        }
        // 简化代码，先禁止取对数
        ui->checkBox_DB->setEnabled(false);
        ui->checkBox_DB->setChecked(false);

        auto enableRadios = [this, &radios]() {
            for (auto* rb : radios)
            {
                rb->setAutoExclusive(true);
                rb->setEnabled(true);
            }};

        switch (resultDataType)
        {
        case 0: // 0:实部
        {
            enableRadios();
            ui->radioButton_RealPart->setChecked(true);
            break;
        }
        case 1:// 1:虚部
        {
            enableRadios();
            ui->radioButton_ImaginaryPart->setChecked(true);
            break;
        }
        case 2:// 2:幅度
        {
            enableRadios();
            ui->radioButton_Amplitude->setChecked(true);
            {
                QSignalBlocker blocker(ui->checkBox_DB);
                ui->checkBox_DB->setEnabled(true);
                ui->checkBox_DB->setChecked(data->getIsLog());
            }
            break;
        }
        case 3:// 3:相位
        {
            enableRadios();
            ui->radioButton_Phase->setChecked(true);
            break;
        }
        case 4://标量
        {
            // 先关闭 autoExclusive，才能把所有都取消选中
            for (auto* rb : radios)
            {
                rb->setAutoExclusive(false);   // 允许“同时不选”
                rb->setChecked(false);         // 取消选中
                rb->setEnabled(false);         // 禁用
                ui->checkBox_DB->setEnabled(true);
                ui->checkBox_DB->setChecked(data->getIsLog());
            }
            break;
        }
        default:
            break;
        }
    }

    void ThreeDCloudMapSidebarSettings::pyDataOprationChanged(bool isLoged, bool isNormalized)
    {
        {
            QSignalBlocker blocker(ui->checkBox_DB);
            ui->checkBox_DB->setChecked(isLoged);
            QSignalBlocker blocker2(ui->checkBox_Normalize);
            ui->checkBox_Normalize->setChecked(isNormalized);
        }
        m_currentItemData->setIsLog(isLoged);
        // m_currentItemData->setIsNormalize(isNormalized);
        emit signal_updateActorValue(m_currentItemData);
    }

    void ThreeDCloudMapSidebarSettings::pyItemCheckStateChanged(int itemIndex, bool visible)
    {
        auto item = ui->listWidget_Data->item(itemIndex);
        {
            QSignalBlocker blocker(ui->listWidget_Data);
            item->setCheckState(visible ? Qt::Checked : Qt::Unchecked);
        }
        siganl_showHideItemActor(item);
    }

} // namespace pst
